package com.docted.seckill.service.impl;

import com.docted.seckill.common.Const;
import com.docted.seckill.dao.SeckillDAO;
import com.docted.seckill.dao.SuccessKillDAO;
import com.docted.seckill.dao.cache.RedisDAO;
import com.docted.seckill.dto.Exposer;
import com.docted.seckill.dto.SeckillExecution;
import com.docted.seckill.entity.Seckill;
import com.docted.seckill.entity.SuccessKilled;
import com.docted.seckill.exception.RepeatKillException;
import com.docted.seckill.exception.SeckillCloseException;
import com.docted.seckill.exception.SeckillException;
import com.docted.seckill.service.SeckillService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


/**
 * Created by DoCted on 2017/5/24
 * Description:
 */

@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(SeckillServiceImpl.class);

    @Autowired
    private SeckillDAO seckillDAO;

    @Autowired
    private SuccessKillDAO successKillDAO;

    @Autowired
    private RedisDAO redisDAO;

    private String salt = "salt";

    @Override
    public List<Seckill> getSeckillList() {
        return seckillDAO.queryAll(0, 4);
    }


    @Override
    public Seckill getSeckillById(Long seckillId) {
        return seckillDAO.queryById(seckillId);
    }


    @Override

    public Exposer exportSeckillUrl(Long seckillId) {

        /**
         * 优化点: 缓存优化
         * get from cache
         * if null
         *      get from db
         * put cache
         *
         * locgoin
         */

        //1.访问redis
        //目前通过超时维护一致性，最简单最常用的方式
        Seckill seckill = redisDAO.getSeckill(seckillId);
        if (seckill == null) {
            seckill = seckillDAO.queryById(seckillId);
            if (seckill == null) {
                return new Exposer(false, seckillId);
            } else {
                redisDAO.putSeckill(seckill);
            }
        }

        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        //系统当前事件
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime()
                || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }

        String md5 = getMD5(seckillId);
        return new Exposer(true, md5, seckillId);
    }

    @Override
    @Transactional
    /**
     * 使用注解控制事务方法的有点：
     * 1.开发团队达成一致约定：明确标注事务方法的变成风格。
     * 2.保证事务方法的执行时间尽可能短，避免穿插其他网络操作：RPC/http请求-redis等等或者玻璃到事务方法的外部，做一个更上层的方法
     * 3.不是所有的方法都需要事务，如果只有一条修改操作，只读操作不需要事务控制
     */
    public SeckillExecution executeSeckill(Long seckillId, Long userPhone, String md5) throws RepeatKillException, SeckillCloseException, SecurityException {

        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            throw new SeckillException("seckill data rewrite");
        }
        /**
         * 秒杀
         * 1.减库存
         * 2.记录秒杀行为
         */
        try {
            //记录购买行为
            int insertCount = successKillDAO.insertSuccessKill(seckillId, userPhone);
            if (insertCount <= 0) {
                //重复秒杀
                throw new RepeatKillException("seckill repeated");
            } else {
                //减库存，热点商品竞争
                Date nowTiem = new Date();
                int updateCount = seckillDAO.reduceNumber(seckillId, nowTiem);
                if (updateCount <= 0) {
                    //秒杀结束
                    throw new SeckillCloseException("seckill is closed");
                } else {
                    //秒杀成功
                    SuccessKilled successKilled = successKillDAO.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, Const.SeckillStatusEnum.SUCCESS.getValue());
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatKillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //抛出业务异常 所有检查异常转化为运行期异常
            throw new SeckillException("seckill inner error : " + e.getMessage());
        }
    }

    private String getMD5(long seckillId) {
        String base = seckillId + "/" + salt;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }


    @Override
    public SeckillExecution executeSeckillProcedure(Long seckillId, Long userPhone, String md5) {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            return new SeckillExecution(seckillId, Const.SeckillStatusEnum.DATA_ILLEGAL.getValue());
        }

        Date killTime = new Date();
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("seckillId", seckillId);
        map.put("phone", userPhone);
        map.put("killTime", killTime);
        map.put("result", null);
        //执行存储过程后 result被赋值
        try {
            seckillDAO.killByProcedure(map);
            int result = MapUtils.getInteger(map, "result", -2);
            if (result == 1) {
                SuccessKilled successKilled = successKillDAO.queryByIdWithSeckill(seckillId, userPhone);
                return new SeckillExecution(seckillId, Const.SeckillStatusEnum.SUCCESS.getCode(), Const.SeckillStatusEnum.SUCCESS.getValue(), successKilled);
            } else {
                return new SeckillExecution(seckillId, Const.SeckillStatusEnum.codeOf(result).getValue());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new SeckillExecution(seckillId, Const.SeckillStatusEnum.INNER_ERROR.getValue());
        }
    }
}
